let request = require('request-promise');
let util = require('util');
let fs = require('fs');
let path = require('path');
let writeFile = util.promisify(fs.writeFile);
let readFile = util.promisify(fs.readFile);

let {appid, appsecret} = require('../config');

module.exports = async (ctx, next) => {
  let data = await readFile(path.resolve(__dirname, '../data.json'), 'utf-8');
        let that = data || JSON.stringify({});
        if (!data) {
            await getToken(ctx, that);
        } else {
            data = JSON.parse(data);
            if (data.expires_in < Date.now()) {
                await getToken(ctx);
            } else {
                ctx.token = data.access_token;
            }
        }
        await next();
}




async function getToken(ctx) {
    let options = {
        method: 'GET',
        uri: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`
    };
    let res = await request(options);
    res = JSON.parse(res);
    ctx.token = res.access_token;
    let time = Date.now() + (res.expires_in - 5 * 60) * 1000;
    data = {access_token: res.access_token, expires_in: time};
    let str = JSON.stringify(data);
    await writeFile(path.resolve(__dirname, '../data.json'), str, 'utf-8');
}
